package com.tanhua.server.service;

import cn.hutool.core.collection.CollUtil;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.tanhua.autoconfig.template.HuanXinTemplate;
import com.tanhua.commons.utils.Constants;
import com.tanhua.dubbo.api.*;
import com.tanhua.model.domain.Announcement;
import com.tanhua.model.domain.User;
import com.tanhua.model.domain.UserInfo;
import com.tanhua.model.enums.CommentType;
import com.tanhua.model.mongo.Comment;
import com.tanhua.model.mongo.Friend;
import com.tanhua.model.vo.*;
import com.tanhua.server.exception.BusinessException;
import com.tanhua.server.interceptor.UserHolder;
import org.apache.dubbo.config.annotation.DubboReference;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

@Service
public class MessagesService {

    @DubboReference
    private UserApi userApi;

    @DubboReference
    private FriendApi friendApi;

    @DubboReference
    private CommentApi commentApi;

    @DubboReference
    private UserInfoApi userInfoApi;

    @DubboReference
    private AnnouncementsApi announcementsApi;

    @Autowired
    private HuanXinTemplate huanXinTemplate;

    /**
     * 根据环信id查询用户详情
     */
    public UserInfoVo findUserInfoByHuanxin(String huanxinId) {
        //1、根据环信id查询用户
        User user = userApi.findByHuanxin(huanxinId);
        //2、根据用户id查询用户详情
        UserInfo userInfo = userInfoApi.findById(user.getId());
        UserInfoVo vo = new UserInfoVo();
        BeanUtils.copyProperties(userInfo,vo); //copy同名同类型的属性
        if(userInfo.getAge() != null) {
            vo.setAge(userInfo.getAge().toString());
        }
        return vo;
    }

    /**
     * 添加好友
     * @param friendId
     */
    public void contacts(Long friendId) {
        Boolean aBoolean = huanXinTemplate.addContact(Constants.HX_USER_PREFIX + UserHolder.getUserId(), Constants.HX_USER_PREFIX + friendId);
        if(!aBoolean){
            throw new BusinessException(ErrorResult.error());
        }
        //若注册成功，记录好友关系到MongoDB
        friendApi.save(UserHolder.getUserId(),friendId);
    }

    /**
     * 分页查询联系人
     * @param page
     * @param pagesize
     * @param keyword
     * @return
     */
    public PageResult findFriends(Integer page, Integer pagesize, String keyword) {
        //调用api查询当前用户的好友信息
        List<Friend> list=friendApi.findByUserId(UserHolder.getUserId(),page,pagesize);
        if(CollUtil.isEmpty(list)){
            return new PageResult();
        }
        //提取数据列表的好友id信息
        List<Long> userIds = CollUtil.getFieldValues(list, "friendId", Long.class);
        //调用userinfoApi的好友详情信息
        UserInfo info = new UserInfo();
        info.setNickname(keyword);
        Map<Long, UserInfo> map = userInfoApi.findByIds(userIds, info);
        //构造vo
        List<ContactVo> vos = new ArrayList<>();
        for (Friend friend : list) {
            UserInfo userInfo = map.get(friend.getFriendId());
            if(userInfo != null) {
                ContactVo vo = ContactVo.init(userInfo);
                vos.add(vo);
            }
        }
        return new PageResult(page,pagesize,0l,vos);
    }

    /**
     * 分页查询点赞列表
     * @param page
     * @param pagesize
     * @return
     */
    public PageResult findLikes(Integer page, Integer pagesize) {
        List<Comment> comments=commentApi.findComments(UserHolder.getUserId().toString(),CommentType.LIKE, page, pagesize);
        //获取评论列表的所有参与评论的用户ID
        if (CollUtil.isEmpty(comments)){
            return new PageResult();
        }
        List<Long> userIds=CollUtil.getFieldValues(comments,"userId",Long.class);
        Map<Long,UserInfo> map=userInfoApi.findByIds(userIds,null);
        List<CommentVo> voList = new ArrayList<>();
        for (Comment comment : comments) {
            UserInfo userInfo = map.get(comment.getUserId());
            if (userInfo!=null){
                CommentVo vo = CommentVo.init(userInfo, comment);
                voList.add(vo);
            }
        }
        return new PageResult(page,pagesize,0L,voList);
    }

    /**
     * 分页查询评论列表
     * @param page
     * @param pagesize
     * @return
     */
    public PageResult findComments(Integer page, Integer pagesize) {
        Long id = UserHolder.getUserId();
        //根据发布人和评论类型去查找
        List<Comment> comments = commentApi.findComments(id.toString(),CommentType.COMMENT,page,pagesize);
        //获取评论列表的所有参与评论的用户ID
        if (CollUtil.isEmpty(comments)){
            return new PageResult();
        }
        List<Long> userIds = CollUtil.getFieldValues(comments, "userId", Long.class);
        Map<Long, UserInfo> map = userInfoApi.findByIds(userIds, null);
        List<CommentVo> voList = new ArrayList<>();
        for (Comment comment : comments) {
            UserInfo userInfo = map.get(comment.getUserId());
            if (userInfo!=null){
                CommentVo vo = CommentVo.init(userInfo, comment);
                voList.add(vo);
            }
        }
        return new PageResult(page,pagesize,0L,voList);

    }

    /**
     * 分页查询喜欢列表
     * @param page
     * @param pagesize
     * @return
     */
    public PageResult findLoves(Integer page, Integer pagesize) {
        List<Comment> comments = commentApi.findComments(UserHolder.getUserId().toString(), CommentType.LOVE, page, pagesize);
        //获取评论列表的所有参与评论的用户ID
        if (CollUtil.isEmpty(comments)){
            return new PageResult();
        }
        List<Long> userIds = CollUtil.getFieldValues(comments, "userId", Long.class);
        Map<Long, UserInfo> map = userInfoApi.findByIds(userIds, null);
        List<CommentVo> voList = new ArrayList<>();
        for (Comment comment : comments) {
            UserInfo userInfo = map.get(comment.getUserId());
            if (userInfo!=null){
                CommentVo vo = CommentVo.init(userInfo, comment);
                voList.add(vo);
            }
        }
        return new PageResult(page,pagesize,0L,voList);

    }

    /**
     * 分页查询公告列表
     * @param page
     * @param pagesize
     * @return
     */
    public PageResult announcements(Integer page, Integer pagesize) {
        Page<Announcement> page1 = announcementsApi.findAllAnnouncements(page, pagesize);
        List<Announcement> list = page1.getRecords();
        if(CollUtil.isEmpty(list)){
            return new PageResult();
        }
        List<AnnouncementVo> voList = new ArrayList<>();

        for (Announcement announcement : list) {
            AnnouncementVo vo = new AnnouncementVo();
            BeanUtils.copyProperties(announcement,vo);
            vo.setCreateDate(String.valueOf(System.currentTimeMillis()));
            voList.add(vo);
        }
        return new PageResult(page,pagesize,page1.getTotal(),voList);

    }

    /**
     * 删除好友
     * @param notLikeuserId
     */
    public void delete(Long notLikeuserId) {
        //删除好友
        friendApi.delete(UserHolder.getUserId(),notLikeuserId);
        //删除环信好友
        Boolean flag = huanXinTemplate.deleteContact(Constants.HX_USER_PREFIX + UserHolder.getUserId(), Constants.HX_USER_PREFIX + notLikeuserId);
    }
}